using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace SrWinGui
{
    public sealed class Impostazioni
    {
        #region classdeclarations
        private static readonly Impostazioni instance = new Impostazioni();
        private Impostazioni()
        {
            dt = new DataTable();
            dt.TableName = "SrwSetting";
            dt.Columns.Add("Name",typeof(System.String));
            dt.Columns.Add("Enabled", typeof(System.Boolean));
            dt.Columns.Add("ExtValue", typeof(System.String));
            dt.PrimaryKey = new DataColumn[] { dt.Columns["Name"] };
            foreach (DataColumn dc in dt.Columns)
                dc.ColumnMapping = MappingType.Attribute;
            
        }
        public static Impostazioni Instance
        {
            get
            {
                return instance;
            }
        }
        #endregion

        private DataTable dt;


        public string GetArguments()
        {            
            string extValue,extValue2,options;
            extValue = extValue2 = options = "";
            
            if (GetExtValue("RipToSingleFile",ref extValue))
                options += " -a " + extValue;

            if (GetBoolValue("DontWriteIndividualTracks"))
                options += " -A";

            if (GetExtValue("DestinationDir", ref extValue))
                options += " -d " + extValue;

            if (GetExtValue("WriteFilesWithPattern", ref extValue))
                options += " -D " + extValue;

            if (GetBoolValue("DontCreateDirForEachStream"))
                options += " -s";

            if (GetExtValue("CreateRelayStream", ref extValue))
                options += " -r " + extValue;

            if (GetExtValue("MaxConnToRelay", ref extValue))
                options += " -R " + extValue;

            if (GetBoolValue("DontScanForFreePorts"))
                options += " -z";

            if (GetExtValue("UseHttpProxy", ref extValue))
                options += " -p " + extValue;

            if (GetExtValue("OverWriteTracksInCompleteDir", ref extValue))
                if (extValue != "" && extValue != "When Larger")
                    options += " -o " + extValue;

            if (GetBoolValue("DontOverwriteTracksInIncomplete"))
                options += " -t";

            if (GetBoolValue("DontAutoReconnect"))
                options += " -c";

            if (GetExtValue("RunForNumberOfSeconds", ref extValue))
                options += " -l " + extValue;

            if (GetExtValue("StopRippingAfterXMb", ref extValue))
                options += " -M " + extValue;

            if (GetExtValue("AddSequenceNumberToOutputFile", ref extValue))
                options += " -q " + extValue;

            if (GetExtValue("UseDifferentUserAgent", ref extValue))
                options += " -u " + extValue;

            if (GetExtValue("TimeOut", ref extValue))
                options += " -m " + extValue;

            if (GetExtValue("SkipFirstXTracks", ref extValue))
                options += " -k " + extValue;

            if (GetBoolValue("TruncateDuplicatedTracks"))
                options += " -T";

            if (GetExtValue("RunExternalCommandForMetaData",ref extValue))
                options += " -E " + extValue;

            if (GetBoolValue("SaveDebug"))
                options += " --debug";

            if (GetBoolValue("DontAddID3Tags"))
                options += " -i";

            if ((extValue = GetStringValue("XsOffset")) != "0")
                options += " --xs_offset="+extValue;
            
            extValue2 = GetStringValue("XsPaddingPost");
            if ((extValue = GetStringValue("XsPaddingPre")) != "300" || extValue2 != "300")
                options += " --xs_padding=" + extValue + ":" + extValue2;

            extValue2 = GetStringValue("XsSearchPost");
            if ((extValue = GetStringValue("XsSearchPre")) != "6000" || extValue2 != "6000")
                options += " --xs_padding=num" + extValue + ":" + extValue2;

            if ((extValue = GetStringValue("XsSilence")) != "1000")
                options += " --xs_silence_length=" + extValue;

            if (GetExtValue("XsCodeSetFileSys", ref extValue))
                options += " --codeset-filesys=" + extValue;

            if (GetExtValue("XsCodeSetId3", ref extValue))
                options += " --codeset-id3=" + extValue;

            if (GetExtValue("XsCodeSetMeta", ref extValue))
                options += " --codeset-metadata=" + extValue;

            if (GetExtValue("XsCodeSetRelay", ref extValue))
                options += " --codeset-relay=" + extValue;

            return options.Replace("  ", " ");
            
        }
        public void Inizializza()
        {
            #region srhelp
/*
Usage: streamripper URL [OPTIONS]
Opts: -h             - Print this listing
      -v             - Print version info and quit
      -a [file]      - Rip to single file, default name is timestamped
      -A             - Don't write individual tracks
      -d dir         - The destination directory
      -D pattern     - Write files using specified pattern
      -s             - Don't create a directory for each stream
      -r [[ip:]port] - Create relay server on base ip:port, default port 8000
      -R #connect    - Max connections to relay, default 1, -R 0 is no limit
      -L file        - Create a relay playlist file
      -z             - Don't scan for free ports if base port is not avail
      -p url         - Use HTTP proxy server at <url>
      -o always      - Always overwrite tracks in complete
      -o never       - Never overwrite tracks in complete
      -t             - Don't overwrite tracks in incomplete
      -c             - Don't auto-reconnect
      -l seconds     - Number of seconds to run, otherwise runs forever
      -M megabytes   - Stop ripping after this many megabytes
      -q [start]     - Add sequence number to output file
      -u useragent   - Use a different UserAgent than "Streamripper"
      -w rulefile    - Parse metadata using rules in file.
      -m timeout     - Number of seconds before force-closing stalled conn
      -k count       - Skip over first <count> tracks before starting to rip
      -T             - Truncate duplicated tracks in incomplete
      -E command     - Run external command to fetch metadata
      --quiet        - Don't print ripping status to console
      --debug        - Save debugging trace
ID3 opts (mp3/aac/nsv):  [The default behavior is adding ID3V2.3 only]
      -i                           - Don't add any ID3 tags to output file
      --with-id3v1                 - Add ID3V1 tags to output file
      --without-id3v2              - Don't add ID3V2 tags to output file
Splitpoint opts (mp3 only):
      --xs-offset=num              - Shift relative to metadata (msec)
      --xs-padding=num:num         - Add extra to prev:next track (msec)
      --xs-search-window=num:num   - Search window relative to metadata (msec)
      --xs-silence-length=num      - Expected length of silence (msec)
Codeset opts:
      --codeset-filesys=codeset    - Specify codeset for the file system
      --codeset-id3=codeset        - Specify codeset for id3 tags
      --codeset-metadata=codeset   - Specify codeset for metadata
      --codeset-relay=codeset      - Specify codeset for the relay stream

*/
            #endregion
            dt.Clear();
            Add("RipToSingleFile",false);
            Add("DontWriteIndividualTracks",false);
            Add("DestinationDir",false);
            Add("WriteFilesWithPattern",false);
            Add("DontCreateDirForEachStream", false);
            Add("CreateRelayStream",false,"8000");
            Add("MaxConnToRelay",false,"1");
            Add("DontScanForFreePorts",false);
            Add("UseHttpProxy",false);
            Add("OverWriteTracksInCompleteDir",false);
            Add("DontOverwriteTracksInIncomplete",false);
            Add("DontAutoReconnect",false);
            Add("RunForNumberOfSeconds",false);
            Add("StopRippingAfterXMb",false);
            Add("AddSequenceNumberToOutputFile",false);
            Add("UseDifferentUserAgent",false);
            Add("TimeOut",false,"20");
            Add("SkipFirstXTracks",false);
            Add("TruncateDuplicatedTracks",false);
            Add("RunExternalCommandForMetaData",false);
            Add("SaveDebug",false);
            Add("DontAddID3Tags",false);
            Add("AddID3V1",false);
            Add("DontAddID3v2",false);
            Add("XsOffset",false,"0");
            Add("XsPaddingPre",false,"300");
            Add("XsPaddingPost",false,"300");
            Add("XsSearchPre",false,"6000");
            Add("XsSearchPost", false, "6000");
            Add("XsSilence",false, "1000");
            Add("XsCodeSetFileSys",false);
            Add("XsCodeSetId3",false);
            Add("XsCodeSetMeta",false);
            Add("XsCodeSetRelay", false);
            Save();
        }        
        
        public void Add(string name, bool value)
        {
            Add(name, value, "");
        }
        public void Add(string name, bool value, string extvalue)
        {
            DataRow dr = dt.NewRow();
            dr["Name"] = name;
            dr["Enabled"] = value;
            dr["ExtValue"] = extvalue;
            dt.Rows.Add(dr);
        }
        
        public void Save()
        {
            dt.WriteXml("SrwSettings.xml");
        }
        public void Load()
        {
            dt.Clear();
            dt.ReadXml("SrwSettings.xml");
        }

        public void Set(string name, bool value)
        {
            Set(name, value, "");
        }
        public void Set(string name, bool value, string extValue)
        {
            DataRow dr = dt.Rows.Find(name);
            if (dr != null)
            {
                dr["Name"] = name;
                dr["Enabled"] = value;
                dr["ExtValue"] = extValue;
            }
        }

        public bool GetBoolValue(string searchValue)
        {
            DataRow dr = getDataValue(searchValue);
            if (dr != null && (bool)dr["Enabled"])
                    return true;
            return false;
        }
        public bool GetExtValue(string searchValue, ref string extendedValue)
        {
            DataRow dr = getDataValue(searchValue);
            if (dr != null)
            {
                extendedValue = dr["ExtValue"].ToString();
                if ((bool)dr["Enabled"])
                    return true;
            }
            else
                extendedValue = "";
            return false;
        }
        public string GetStringValue(string searchValue)
        {
            DataRow dr = getDataValue(searchValue);
            if (dr == null)
                return "";
            return dr["ExtValue"].ToString();
        }
        private DataRow getDataValue(string searchValue)
        {
            return dt.Rows.Find(searchValue);
        }
    }
}
/*
RipToSingleFile
DontWriteIndividualTracks
DestinationDir
WriteFilesWithPattern
DontCreateDirForEachStream
CreateRelayStream
MaxConnToRelay
DontScanForFreePorts
UseHttpProxy
OverWriteTracksInCompleteDir
DontOverwriteTracksInIncomplete
DontAutoReconnect
RunForNumberOfSeconds
StopRippingAfterXMb
AddSequenceNumberToOutputFile
UseDifferentUserAgent
TimeOut
SkipFirstXTracks
TruncateDuplicatedTracks
RunExternalCommandForMetaData
SaveDebug
DontAddID3Tags
AddID3V1
DontAddID3v2
XsOffset
XsPaddingPre
XsPaddingPost
XsSearchPre
XsSearchPost
XsSilence
XsCodeSetFileSys
XsCodeSetId3
XsCodeSetMeta
XsCodeSetRelay
*/